<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query.id">新增纸张内部调拨单</div>
            <div v-else>
              <span
                class="text-sm mr-2"
                style="color: var(--el-text-color-regular)"
              >
                纸张内部调拨单编码:
              </span>
              <el-tag>{{ route.query.code }}</el-tag>
            </div>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center" v-if="!route.query.readonly">
            <el-button type="primary" :loading="btnLoading" @click="submitForm"
              >保 存</el-button
            >
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="route.query.readonly"
              ref="materialReceiptRef"
              label-width="100px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="调出机台" prop="outMachineName">
                    <el-input
                      v-model="form.outMachineName"
                      @change="handleValidate"
                      placeholder="选择调出机台"
                      @click="
                        () => {
                          (chu = true), (workBenchDialog = true);
                        }
                      "
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="调出车间">
                    <el-input
                      v-model="form.cworkshopName"
                      disabled
                      placeholder="自动带出"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="调入机台" prop="enterMachineName">
                    <el-input
                      v-model="form.enterMachineName"
                      @change="handleValidate"
                      placeholder="选择调入机台"
                      @click="
                        () => {
                          (ru = true), (workBenchDialog2 = true);
                        }
                      "
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="调入车间">
                    <el-input
                      v-model="form.rworkshopName"
                      disabled
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="调拨日期" prop="allotDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.allotDate"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetime"
                      placeholder="请选择时间"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="操作人" prop="createBy">
                    <el-input
                      v-model="form.createBy"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="调拨明细" name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">调拨明细</span>
          </template>
          <el-button
            style="margin-bottom: 10px"
            type="primary"
            size="small"
            @click="handlePaper"
            :disabled="route.query.readonly"
          >
            从机台纸库选择
          </el-button>
          <el-table
            v-loading="loading"
            class="table-form"
            :data="mesInnerallotDetailList"
          >
            <el-table-column
              label="序号"
              width="60"
              type="index"
              align="center"
            ></el-table-column>
            <el-table-column
              label="纸张编码"
              width="120"
              align="center"
              prop="code"
            ></el-table-column>
            <el-table-column label="纸张名称" align="center" prop="name" />
            <el-table-column label="规格型号" align="center" prop="specs">
              <template #default="scope">
                <dict-tag :options="mes_paper_specs" :value="scope.row.specs" />
              </template>
            </el-table-column>
            <el-table-column label="纸张品牌" align="center" prop="brand">
              <template #default="scope">
                <dict-tag :options="mes_paper_brand" :value="scope.row.brand" />
              </template>
            </el-table-column>
            <el-table-column label="计量单位" align="center" prop="unit">
              <template #default="scope">
                <dict-tag :options="mes_paper_unit" :value="scope.row.unit" />
              </template>
            </el-table-column>
            <el-table-column prop="lnumber" align="center" width="120">
              <template #header>
                <div>
                  令/件
                  <br />
                  kg/卷筒
                </div>
              </template>
              <template #default="scope">
                <el-input
                  v-model="scope.row.lnumber"
                  @change="sumQuantity(scope.row)"
                  :disabled="route.query.readonly"
                  type="number"
                  placeholder="请输入数量"
                />
              </template>
            </el-table-column>
            <el-table-column prop="jnumber" disabled align="center" width="120">
              <template #header>
                <div>
                  件数
                  <br />
                  卷筒数
                </div>
              </template>
              <template #default="scope">
                <el-input
                  v-model="scope.row.jnumber"
                  @change="sumQuantity(scope.row)"
                  :disabled="route.query.readonly"
                  type="number"
                  placeholder="请输入数量"
                />
              </template>
            </el-table-column>
            <el-table-column prop="odd" disabled align="center" width="120">
              <template #header>
                <div>
                  零头(令)
                  <br />
                  零头(kg)
                </div>
              </template>
              <template #default="scope">
                <el-input
                  v-model="scope.row.odd"
                  @change="sumQuantity(scope.row)"
                  :disabled="route.query.readonly"
                  type="number"
                  placeholder="请输入数量"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="allotNumber"
              disabled
              align="center"
              width="120"
            >
              <template #header>
                <div>
                  总数量(令)
                  <br />
                  总数量(kg)
                </div>
              </template>
            </el-table-column>

            <el-table-column
              label="备注"
              prop="remark"
              align="center"
              width="120"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.remark"
                  :disabled="route.query.readonly"
                  placeholder="请输入备注"
                />
              </template>
            </el-table-column>

            <el-table-column
              label="操作"
              align="center"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                    :disabled="route.query.readonly"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <benchPaper
      :visible="PaperDialog"
      :outMachineid="form.outMachineid"
      @changeUpdate="changebenchPaperData"
      @cancel="
        () => {
          PaperDialog = false;
        }
      "
    ></benchPaper>
    <SearchWorkBench
      :visible="workBenchDialog"
      @changeUpdate="choiceWorkBench"
      @cancel="
        () => {
          workBenchDialog = false;
        }
      "
    ></SearchWorkBench>
    <SearchWorkBench2
      :visible="workBenchDialog2"
      @changeUpdate="choiceWorkBench2"
      @cancel="
        () => {
          workBenchDialog2 = false;
        }
      "
    ></SearchWorkBench2>
  </div>
</template>
<script setup>
import {
  getIdInnerallot,
  addInnerallot,
  updateInnerallot,
} from "@/api/storage/internalTransfer.js";
import benchPaper from "./benchPaper";
const ru = ref(false);
const chu = ref(false);

import SearchWorkBench from "@/components/SearchWorkBench";
import SearchWorkBench2 from "@/components/SearchWorkBench";
import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import { ElMessage } from "element-plus";
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const { mes_paper_unit, mes_paper_specs, mes_paper_brand } = proxy.useDict(
  "mes_paper_unit",
  "mes_paper_specs",
  "mes_paper_brand"
);
const route = useRoute();
const router = useRouter();
const activeNames = ["1", "2"];
const materialReceiptRef = ref(null);
const loading = ref(false);
const userInfo = useUserStore();
const mesInnerallotDetailList = ref([]);
const PaperDialog = ref(false);
const btnLoading = ref(false);
const workBenchDialog = ref(false);
const workBenchDialog2 = ref(false);
const data = reactive({
  form: {},
  rules: {
    outMachineName: [
      { required: true, message: "调出机台不能为空", trigger: "change" },
    ],
    enterMachineName: [
      {
        required: true,
        message: "调入机台不能为空",
        trigger: ["blur", "change"],
      },
    ],
    allotDate: [
      { required: true, message: "调拨日期不能为空", trigger: "change" },
    ],
    createBy: [
      { required: true, message: "操作人不能为空", trigger: "change" },
    ],
  },
});
const { form, rules } = toRefs(data);
if (route.query.id) {
  getIdInnerallot(route.query.id).then((response) => {
    form.value = response.data;
    form.value.outMachineName = response.data.cmachineName;
    form.value.enterMachineName = response.data.rmachineName;
    mesInnerallotDetailList.value = response.data.mesInnerallotDetailList;
    mesInnerallotDetailList.value.forEach((item) => {
      Object.assign(item, item.mesPaper);
    });
  });
} else {
  form.value = {};
  form.value.createBy = userInfo.name;
}
// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  form.value.allotDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
//选择机台
const choiceWorkBench = (row) => {
  form.value.outMachineid = row.pid;
  form.value.outMachineName = row.machineName;
  form.value.cworkshopName = row.workshopName;
  workBenchDialog.value = false;
};
const choiceWorkBench2 = (row) => {
  form.value.enterMachineid = row.pid;
  form.value.enterMachineName = row.machineName;
  form.value.rworkshopName = row.workshopName;
  workBenchDialog2.value = false;
};
const handleValidate = () => {
  if (form.value.outMachineid === form.value.enterMachineid) {
    ElMessage({
      message: "调入机台与调出机台不能相同 请重新选择",
      type: "warning",
    });
    form.value.outMachineid = "";
    form.value.outMachineName = "";
    form.value.cworkshopName = "";
    form.value.enterMachineid = "";
    form.value.enterMachineName = "";
    form.value.rworkshopName = "";
  }
};
//选择机台纸张
const handlePaper = () => {
  PaperDialog.value = true;
};
const changebenchPaperData = (row) => {
  console.log("row", row);
  mesInnerallotDetailList.value.push(row);
  mesInnerallotDetailList.value.forEach((item) => {
    item.paperid = item.id;
  });
  PaperDialog.value = false;
};
const sumQuantity = (row) => {
  row.allotNumber =
    Number(row.lnumber || 0) * Number(row.jnumber || 0) + Number(row.odd || 0);
};
// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    mesInnerallotDetailList.value = mesInnerallotDetailList.value.filter(
      (item) => item.id !== row.id
    );
    proxy.$modal.msgSuccess("删除成功");
  });
};
// 确认
const submitForm = () => {
  materialReceiptRef.value.validate((valid) => {
    if (valid) {
      btnLoading.value = true;
      if (route.query.id) {
        updateInnerallot({
          ...form.value,
          mesInnerallotDetailList: mesInnerallotDetailList.value,
        })
          .then((res) => {
            ElMessage({
              message: "编辑成功",
              type: "success",
            });
            goBack();
          })
          .catch((err) => {
            btnLoading.value = false;
          });
      } else {
        addInnerallot({
          ...form.value,
          status: 1,
          mesInnerallotDetailList: mesInnerallotDetailList.value,
        })
          .then((res) => {
            ElMessage({
              message: "新增成功",
              type: "success",
            });
            goBack();
          })
          .catch((err) => {
            btnLoading.value = false;
          });
      }
    }
  });
};

// const must = obj => {
//     let mustColumns = []
//     mustColumns = [8, 9, 10, 11]
//     if (mustColumns.includes(obj.columnIndex)) {
//         return 'must'
//     }
// }
//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
  // router.push('/storage/internalTransfer')
};
getCurrentDateTime();
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}

:deep(.el-pagination) {
  position: unset;
}

.table-form :deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-table th.must div:before) {
  content: "*";
  color: #ff1818;
}
</style>
